//
//  MYLoopImages.m
//  Stock_Stategy
//
//  Created by MayerF on 2017/5/31.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "MYLoopImages.h"

typedef NS_ENUM(NSInteger, kTransformType) {
    kTransform_no_Type,     //没有滑动到两侧不切换
    kTransform_left_Type,   //scrollview显示最左侧切换
    kTransform_right_Type,  //scrollview显示最右侧切换
};

@interface MYLoopImages()<UIScrollViewDelegate>
@property (nonatomic, strong)UIScrollView *pScrollView;
@property (nonatomic, strong)UIView *pContentSizeView;
@property (nonatomic, strong)UIPageControl *pPageControl;
@property (nonatomic, strong)UIImageView *pLeftImageView;
@property (nonatomic, strong)UIImageView *pCurrentImageView;
@property (nonatomic, strong)UIImageView *pRightImageView;

@property (nonatomic, strong)NSTimer *pTimer;
@property (nonatomic, copy)ClickImageBlock clickImageBlock;

@property (nonatomic, strong)NSArray *pImagesArray;
@property (nonatomic, assign)NSInteger nCurrentIndex; //当前显示图片的下标
@property (nonatomic, assign)NSInteger nLeftIndex;
@property (nonatomic, assign)NSInteger nRightIndex;
@property (nonatomic, assign)kTransformType nTransformType;
@end

@implementation MYLoopImages

#pragma mark -
#pragma mark init
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self p_commonInit];
    }
    return self;
}
- (void)p_commonInit
{
    _pScrollView = [UIScrollView new];
    _pContentSizeView = [UIView new];
    _pLeftImageView = [UIImageView new];
    _pCurrentImageView = [UIImageView new];
    _pRightImageView = [UIImageView new];
    
    _pScrollView.delegate = self;
    _pScrollView.pagingEnabled = YES;
    _pScrollView.showsHorizontalScrollIndicator = NO;
//    _pLeftImageView.contentMode = UIViewContentModeScaleAspectFit;
//    _pCurrentImageView.contentMode = UIViewContentModeScaleAspectFit;
//    _pRightImageView.contentMode = UIViewContentModeScaleAspectFit;
    
    [self addSubview:_pScrollView];
    [_pScrollView addSubview:_pContentSizeView];
    [_pContentSizeView addSubview:_pLeftImageView];
    [_pContentSizeView addSubview:_pRightImageView];
    [_pContentSizeView addSubview:_pCurrentImageView];
    
    [self p_initContraints];
    
    _changeTime = 2;
    _nTransformType = kTransform_no_Type;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture)];
    [_pScrollView addGestureRecognizer:tapGesture];
    
}
- (void)p_initContraints
{
    [_pScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
    [_pContentSizeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(_pScrollView);
        make.height.mas_equalTo(_pScrollView);
        make.width.mas_equalTo(_pScrollView).multipliedBy(3);
    }];
    [_pLeftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.mas_equalTo(_pContentSizeView);
        make.right.mas_equalTo(_pCurrentImageView.mas_left);
    }];
    [_pRightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.mas_equalTo(_pContentSizeView);
    }];
    [_pCurrentImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(_pContentSizeView);
        make.right.mas_equalTo(_pRightImageView.mas_left);
        make.width.mas_equalTo(@[_pLeftImageView, _pRightImageView]);
    }];
}
#pragma mark -
#pragma mark public
- (void)showImages:(NSArray<NSString *>*)images
        clickImage:(ClickImageBlock)clickImageBlock
{
    _clickImageBlock = clickImageBlock;
    [self showImages:images];
}
- (void)showImages:(NSArray<NSString *>*)images
{
    _pImagesArray = images;
    _pScrollView.scrollEnabled = YES;
    if (images.count == 0) { return;}
    if (images.count == 1) {
        if ([_pTimer isValid]) {
            [self p_pauseTimer];
        }
        _pScrollView.scrollEnabled = NO;
        _pCurrentImageView.image = [UIImage imageNamed:_pImagesArray[0]];
    }else {
        _nCurrentIndex = 0;
        _nLeftIndex = _nCurrentIndex - 1 < 0 ? (_pImagesArray.count - 1) : _nCurrentIndex - 1;
        _nRightIndex = _nCurrentIndex + 1 > (_pImagesArray.count-1) ? (0) : _nCurrentIndex + 1;
        _pLeftImageView.image = [UIImage imageNamed:_pImagesArray[_nLeftIndex]];
        _pCurrentImageView.image = [UIImage imageNamed:_pImagesArray[_nCurrentIndex]];
        _pRightImageView.image = [UIImage imageNamed:_pImagesArray[_nRightIndex]];
        [self p_startTimer];
    }
    self.pPageControl.numberOfPages = images.count;
    self.pPageControl.currentPage = 0;
}
// 设置pageControl的指示器图片
- (void)setPageImage:(UIImage *)image andCurrentPageImage:(UIImage *)currentImage {
    if (!image || !currentImage) return;
//    self.pageImageSize = image.size;
    [self.pPageControl setValue:currentImage forKey:@"_currentPageImage"];
    [self.pPageControl setValue:image forKey:@"_pageImage"];
}
// 设置pageControl的指示器颜色
- (void)setPageColor:(UIColor *)color andCurrentPageColor:(UIColor *)currentColor {
    self.pPageControl.pageIndicatorTintColor = color;
    self.pPageControl.currentPageIndicatorTintColor = currentColor;
}
#pragma mark -
#pragma mark action
- (void)timerAction
{
    DLog(@"timerAction");
    if (_pScrollView.contentOffset.x == CGRectGetWidth(self.frame)) {
        [_pScrollView setContentOffset:CGPointMake(CGRectGetWidth(self.frame)*2, 0) animated:YES];
    }else if (_pScrollView.contentOffset.x == CGRectGetWidth(self.frame)*2) {
        [self p_transformWithType:kTransform_right_Type];
        [_pScrollView setContentOffset:CGPointMake(CGRectGetWidth(self.frame)*2, 0) animated:YES];
    }else if (_pScrollView.contentOffset.x == 0) {
        [_pScrollView setContentOffset:CGPointMake(CGRectGetWidth(self.frame), 0) animated:YES];
    }
}
- (void)tapGesture
{
    NSString *imageName = _pImagesArray[_pPageControl.currentPage];
    if (_clickImageBlock) {
        _clickImageBlock(imageName);
    }
}
#pragma mark -
#pragma mark private
- (void)p_startTimer
{
    if (!_pTimer) {
        _pTimer = [NSTimer timerWithTimeInterval:_changeTime target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_pTimer forMode:NSRunLoopCommonModes];
    }
}
- (void)p_pauseTimer
{
    if ([_pTimer isValid]) {
        _pTimer.fireDate = [NSDate distantFuture];
    }
}
- (void)p_resumeTimer
{
    if ([_pTimer isValid]) {
        _pTimer.fireDate = [NSDate distantPast];
    }
}
- (void)p_scrollWithOffsetX:(CGFloat)offsetX
{
    //调整图片切换逻辑
    if (offsetX < 0) {
        [self p_transformWithType:kTransform_left_Type];
    }else if (offsetX > CGRectGetWidth(self.frame)*2) {
        [self p_transformWithType:kTransform_right_Type];
    }
    //调整PageControl切换逻辑
    if (offsetX > CGRectGetWidth(self.frame)*3/2) {
        self.pPageControl.currentPage = _nCurrentIndex + 1 > (_pImagesArray.count-1) ? (0) : _nCurrentIndex + 1;
    }else if (offsetX < CGRectGetWidth(self.frame)/2) {
        self.pPageControl.currentPage = _nCurrentIndex - 1 < 0 ? (_pImagesArray.count - 1) : _nCurrentIndex - 1;
    }else {
        self.pPageControl.currentPage = _nCurrentIndex;
    }
}
- (void)p_transformWithType:(kTransformType)type
{
    if (type == kTransform_left_Type) {
        _nCurrentIndex = _nLeftIndex;
    }else if (type == kTransform_right_Type) {
        _nCurrentIndex = _nRightIndex;
    }
    _nRightIndex = _nCurrentIndex + 1 > (_pImagesArray.count-1) ? (0) : _nCurrentIndex + 1;
    _nLeftIndex = _nCurrentIndex - 1 < 0 ? (_pImagesArray.count - 1) : _nCurrentIndex - 1;
    _pCurrentImageView.image = [UIImage imageNamed:_pImagesArray[_nCurrentIndex]];
    _pLeftImageView.image = [UIImage imageNamed:_pImagesArray[_nLeftIndex]];
    _pRightImageView.image = [UIImage imageNamed:_pImagesArray[_nRightIndex]];
    _pScrollView.contentOffset = CGPointMake(CGRectGetWidth(self.frame), 0);
}

#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self p_pauseTimer];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self p_scrollWithOffsetX:scrollView.contentOffset.x];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self p_resumeTimer];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _pScrollView.contentOffset = CGPointMake(CGRectGetWidth(self.frame), 0);
}
#pragma mark -
#pragma mark lazy
- (UIPageControl *)pPageControl
{
    if (!_pPageControl) {
        _pPageControl = [UIPageControl new];
        _pPageControl.userInteractionEnabled = NO;
        [self setPageColor:[UIColor brownColor] andCurrentPageColor:[UIColor redColor]];
        [self addSubview:_pPageControl];
        [_pPageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self);
            make.bottom.mas_equalTo(self).offset(-5);
            make.width.mas_equalTo(50);
            make.height.mas_equalTo(10);
        }];
    }
    return _pPageControl;
}

- (void)dealloc {
    if ([_pTimer isValid]) {
        [_pTimer invalidate];
        _pTimer = nil;
    }
}

@end
